import React from 'react'
import { connect } from 'react-redux'
import { List, Badge } from 'antd-mobile'

const Item = List.Item
const Brief = Item.Brief



function Message(props) {
    const { userInfo } = props.user
    const { users, chatMsg } = props.chat

    function getLastMsgs(user_id) {
        let lastMsgObj = {}
        chatMsg.forEach(msg => {
            if (lastMsgObj[msg.chat_id]) {
                let unreadCount = lastMsgObj[msg.chat_id].unreadCount
                if (lastMsgObj[msg.chat_id].create_time < msg.create_time) {
                    lastMsgObj[msg.chat_id] = msg
                }
                lastMsgObj[msg.chat_id].unreadCount = !msg.read && msg.to === user_id ? unreadCount + 1 : unreadCount
            } else {
                lastMsgObj[msg.chat_id] = msg
                lastMsgObj[msg.chat_id].unreadCount = !msg.read && msg.to === user_id ? 1 : 0
            }
        })

        console.log(lastMsgObj);
        const lastMsgs = Object.values(lastMsgObj)

        lastMsgs.sort(function (m1, m2) { // 如果结果<0, 将m1放在前面, 如果结果为0, 不变, 如果结果>0, m2前面
            return m2.create_time - m1.create_time
        })
        console.log(lastMsgs)
        return lastMsgs
    }

    if(!userInfo){
        return null
    }
    let lastMsgs = getLastMsgs(userInfo._id)

    return  <div>
        <List>
            {
                lastMsgs.map(msg => {
                    // 得到目标用户的id
                    const targetUserId = msg.to === userInfo._id ? msg.from : msg.to
                    // 得到目标用户的信息
                    const targetUser = users[targetUserId] || {}
                    return (
                        <Item
                            key={msg.chat_id}
                            extra={<Badge text={msg.unreadCount} />}
                            thumb={targetUser.header ? <img src={require(`../../assets/images/${targetUser.header}.png`)} /> : null}
                            arrow='horizontal'
                            onClick={() => props.history.push(`/chat/${targetUserId}`)}
                        >
                            {msg.content}
                            <Brief>{targetUser.username}</Brief>
                        </Item>
                    )
                })
            }
        </List>
    </div>
}

export default connect(
    state => ({ user: state.user, chat: state.chat }),
    {}
)(Message)